import React, {useState, useEffect, useRef} from 'react'
import {Table, Button, Modal, Input, Form, message, Space} from 'antd'
import {useNavigate} from 'react-router-dom';
import TheQueryForm from '@/components/TheQueryForm'
import TheImage from '@/components/TheImage'
import ApplyRecord from './components/applyRecord';
import copy from 'copy-to-clipboard';

import {
    goodsManagementPage,
    getStoreGoodsOnShelf,
    getStoreGoodsOffShelf,
    goodsApplyOnShelf,
    goodsCancelApplyOnShelf,
    goodsClassifyList,
    getStoreGoodsDetails,
    getSharVirtualProductPass
} from '@/api/goodsManagement/goodsList.js';
import {set} from 'lodash';
import TheButton from "@/components/TheButton/index.jsx";
import {Decimal} from "decimal.js";

const {TextArea} = Input;

export default function goodsManagement() {
    const navigate = useNavigate();
    const FormRef = useRef()
    const SearchFormRef = useRef()
    const columns = [
        {
            title: '商品ID',
            dataIndex: 'goodsId',
            key: 'goodsId',
        },
        {
            title: '商品名称',
            dataIndex: 'goodsName',
            key: 'goodsName',
            width: 300,
        },
        {
            title: '商品图片',
            dataIndex: 'goodsShowImages',
            key: 'goodsShowImages',
            render: (text) => {
                let arr = text.split(',')
                return <TheImage src={[arr[0]]} width={80} height={80}/>
            }
        },
        {
            title: '类目',
            dataIndex: 'goodsClassifyName',
            key: 'goodsClassifyName',
        },
        {
            title: '状态',
            dataIndex: 'goodsStatus',
            key: 'goodsStatus',
            render: (text) => {
                let label = ''
                switch (text) {
                    case 'Y':
                        label = "上架"
                        break
                    case 'N':
                        label = '下架'
                        break
                    case 'P':
                        label = "平台方已下架"
                        break
                    case 'A':
                        label = '申请上架中'
                        break
                    default:
                        label = '-'
                }
                return label
            }

        },
        {
            title: '最近操作时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (text) => {
                return text ? text : '-'
            }
        },
        {
            title: '操作',
            width: 380,
            flex: 'right',
            render(text, record, index) {
                return (
                    <div>
                        {
                            record.isVirtual && <TheButton type="link" onClick={() => {
                                openCopyModal(record)
                            }}>复制</TheButton>
                        }
                        {
                            (record.goodsStatus === 'A' && record.storeStatus === 'Y') ? null :
                                <TheButton haspermi={['goodsManagement:goodsList:edit']} type="link" onClick={() => {
                                    navigate('/goodsList/editGoods', {
                                        state: {
                                            mode: 'edit',
                                            id: record.goodsId,
                                            storeId: record.storeGoodsId
                                        }
                                    })
                                }}>修改</TheButton>
                        }
                        <TheButton haspermi={['goodsManagement:goodsList:view']} type="link" onClick={() => {
                            navigate('/goodsList/detailsGoods', {
                                state: {
                                    id: record.goodsId,
                                    storeId: record.storeGoodsId
                                }
                            })
                        }}>商品详情</TheButton>
                        {record.goodsStatus === 'Y' &&
                            <TheButton haspermi={['goodsManagement:goodsList:offShelves']} type="link"
                                    loading={record.onOffLoading}
                                    onClick={() => soldOut(record.storeGoodsId, index)}>下架</TheButton>}
                        {(record.goodsStatus === 'N' && record.storeStatus === 'Y') &&
                            <TheButton haspermi={['goodsManagement:goodsList:onShelves']} type="link"
                                    loading={record.onOffLoading}
                                    onClick={() => putAway(record.storeGoodsId, index)}>上架</TheButton>}
                        {record.hasPutawayAuditRecord &&
                            <TheButton haspermi={['goodsManagement:goodsList:record']} type="link" onClick={() => {
                                applyRecord(record.storeGoodsId)
                            }}>查看记录</TheButton>}
                        {(record.goodsStatus === 'A' && record.storeStatus === 'Y') &&
                            <TheButton haspermi={['goodsManagement:goodsList:cancelApply']} type="link"
                                    loading={record.cancelApplyLoading}
                                    onClick={() => cancelApplyPutAwayModal(record.storeGoodsId, index)}>取消申请上架</TheButton>}
                        {(record.goodsStatus === 'P' && record.storeStatus === 'Y') &&
                            <TheButton haspermi={['goodsManagement:goodsList:applyPutAway']} type="link"
                                    onClick={() => applyPutAway(record.storeGoodsId)}>申请上架</TheButton>}
                    </div>
                )
            }
        },
    ]//表头
    const searchOption = [
        {
            field: 'goodsIdOrName',
            label: '商品信息',
            placeholder: '商品ID/商品名称',
            type: 'Input',
            key: 'goodsIdOrName',
        },
        {
            field: 'classifyId',
            key: 'goodsClassifyId',
            label: '所属类目',
            placeholder: '全部',
            type: 'Select',
            options: [{goodsClassifyName: '全部', goodsClassifyId: ' ', key: 'goodsClassifyId'}],
            txt: 'goodsClassifyName',
            value: 'goodsClassifyId',
            api: goodsClassifyList,
            params: {level: '2'},
        },
        {
            field: 'goodsStatus',
            key: 'goodsStatus',
            label: '状态',
            placeholder: '全部',
            type: 'Select',
            options: [
                {value: '', label: '全部'},
                {value: 'Y', label: '上架'},
                {value: 'N', label: '下架'},
                {value: 'P', label: '平台方已下架'},
                {value: 'A', label: '申请上架中'}
            ]
        },
    ] //搜索项

    const [queryForm, setQueryForm] = useState({}) //搜索值
    const [dataSource, setDataSource] = useState([]); // 表格数据
    const [pageData, setPageData] = useState({pageNo: 1, pageSize: 10, total: 0}) //分页参数
    const [applyPutAwayModal, setApplyPutAwayModal] = useState(false) //申请上架弹窗是否显示
    const [storeGoodsId, setStoreGoodsId] = useState('') //店铺商品主键id
    const [applyPutAwayLoading, setApplyPutAwayLoading] = useState(false) //申请上架loading
    const [applyRecordModal, setApplyRecordModal] = useState(false) //申请记录弹窗
    const [copySkuModal, setCopySkuModal] = useState(false) //复制功能弹窗
    const [copyDataSource, setCopyDataSource] = useState(false) //复制功能弹窗表格
    const [copyColumns, setCopyColumns] = useState([]); // 复制功能弹窗表格表头

    useEffect(() => {
        getData({...pageData})
    }, [])

    const getData = async (values) => {
        if (values && values.hasOwnProperty('total')) {
            delete values.total
        }
        await goodsManagementPage({...values}).then(res => {
            if (res.code === 0 && res.data) {
                setDataSource(res.data)
                setPageData({
                    pageNo: res.pageNo,
                    pageSize: res.pageSize,
                    total: res.totalCount
                })
            }
        })
    }
    // 搜索
    const onFormSearch = (values) => {
        setQueryForm({...values})
        getData({pageNo: 1, pageSize: 10, ...values})
    }
    // 搜索重置
    const onReset = () => {
        getData({pageNo: 1, pageSize: 10,})
        setQueryForm({})
    }
    // 分页切换
    const pageChange = async (pageNo, pageSize) => {
        await getData({
            pageNo,
            pageSize,
            ...queryForm,
        }).then(() => {
            setPageData({
                pageNo,
                pageSize,
                total: pageData.total,
            })
        })
    }
    // 上架
    const putAway = (storeGoodsId, index) => {
        loadingSet(index, true, 'onOff')
        setTimeout(async () => {
            await getStoreGoodsOnShelf({storeGoodsId}).then((res) => {
                if (res.code === 0) {
                    message.success('上架成功');
                    pageChange(1, 10)
                }
                loadingSet(index, false, 'onOff')
            })
        }, 500)
    }
    // 申请上架弹窗
    const applyPutAway = (storeGoodsId) => {
        setStoreGoodsId(storeGoodsId)
        setApplyPutAwayModal(true)
    }
    // 取消申请上架
    const cancelApplyPutAwayModal = (storeGoodsId, index) => {
        loadingSet(index, true, 'cancelApply')
        Modal.confirm({
            title: '取消上架申请',
            content: '是否确认取消该商品的上架申请？',
            onOk: async () => {
                await goodsCancelApplyOnShelf({storeGoodsId}).then(res => {
                    if (res.code === 0) {
                        message.success('已取消上架申请')
                        getData({...pageData})
                    }
                })
                loadingSet(index, false, 'cancelApply')
            },
            onCancel: () => {
                loadingSet(index, false, 'cancelApply')
            }
        })
    }
    // 确认保存申请上架说明
    const saveApplyPutAway = () => {
        FormRef.current.validateFields().then(async (value) => {
            if (value.explain.length > 500) {
                message.error('申请说明输入不能超过500字！')
                return false
            }
            setApplyPutAwayLoading(true);
            await goodsApplyOnShelf({...value, storeGoodsId}).then(res => {
                if (res.code === 0) {
                    message.success('上架申请中');
                    getData({...pageData})
                    FormRef.current.resetFields()
                }
                setApplyPutAwayModal(false)
            })
            setApplyPutAwayLoading(false);
        })
    }
    // 取消、关闭申请上架
    const cancelApplyPutAway = () => {
        FormRef.current.resetFields()
        setApplyPutAwayModal(false)
    }
    //表格按钮loading防连点
    const loadingSet = (index, flag, type) => {
        if (type === 'onOff') {
            dataSource[index].onOffLoading = flag
        }
        if (type === 'cancelApply') {
            dataSource[index].cancelApplyLoading = flag
        }
        setDataSource([...dataSource])
    }
    // 下架
    const soldOut = (storeGoodsId, index) => {
        loadingSet(index, true, 'onOff')
        Modal.confirm({
            title: '下架提醒',
            content: '商品下架后，可能会影响正在购买的用户，是否下架？',
            okText: '下架',
            onOk: async () => {
                await getStoreGoodsOffShelf({storeGoodsId}).then((res) => {
                    if (res.code === 0) {
                        message.success('商品已下架')
                        pageChange(1, 10)
                    }
                })
                loadingSet(index, false, 'onOff')
            },
            onCancel: () => {
                loadingSet(index, false, 'onOff')
            }
        })
    }
    //查看记录
    const applyRecord = (storeGoodsId) => {
        setStoreGoodsId(storeGoodsId)
        setApplyRecordModal(true)
    }
    // 打开复制功能弹窗
    const openCopyModal = async (record) => {
        setCopySkuModal(true)
        setStoreGoodsId(record.storeGoodsId)
        getStoreGoodsDetails({ goodsId:record.goodsId, storeGoodsId:record.storeGoodsId }).then(res => {
            if (res.code === 0 && res.data) {
                let skuInfoVo = res.data.nonSelfGoodsSkuDTOList
                let column = [] //表格表头处理
                skuInfoVo[0].skuAttribute.forEach((item, index) => {
                    column.push({
                        title: item.key,
                        dataIndex: index,
                        key: index,
                    })
                });
                column = column.concat([
                    {
                        title: '划线价（元）',
                        dataIndex: 'skuOriginalPrice',
                        key: 'skuOriginalPrice',
                    },
                    {
                        title: '日常价（元）',
                        dataIndex: 'skuCurrentPrice',
                        key: 'skuCurrentPrice',
                    },
                    {
                        title: '库存',
                        dataIndex: 'skuStock',
                        key: 'skuStock',
                    },
                    {
                        title: '重量（kg）',
                        dataIndex: 'skuWeight',
                        key: 'skuWeight',
                    },
                    {
                        title: '描述',
                        dataIndex: 'skuDescription',
                        key: 'skuDescription',
                    },
                    {
                        title: '图片',
                        dataIndex: 'imageFile',
                        key: 'imageFile',
                    },
                    {
                        title: '操作',
                        flex: 'right',
                        render(text, record, index) {
                            return <Button type={'link'} onClick={()=>copyClipboard(record)}>复制</Button>
                        }
                    }
                ])
                setCopyColumns(column)
                let dataSource = skuInfoVo.map((v, i) => {
                    let obj = {};
                    v.skuAttribute.forEach((j, k) => {
                        obj[k] = j.value;
                    });
                    obj.skuCurrentPrice = '￥' + Decimal(v.skuCurrentPrice).div(Decimal(100)).toNumber().toFixed(2) //日常价
                    obj.skuOriginalPrice = '￥' + Decimal(v.skuOriginalPrice).div(Decimal(100)).toNumber().toFixed(2) //划线价
                    obj.skuStock = parseInt(v.skuStock).toLocaleString(); //可用库存
                    obj.skuWeight = `${v.skuWeight / 1000}kg`; //重量
                    obj.skuDescription = v.skuDescription; //描述
                    obj.imageFile = <TheImage src={[v.imageFile]}></TheImage> //图片
                    obj.id = i
                    obj.skuId = v.skuId
                    return obj;
                });
                setCopyDataSource(dataSource)
            }
        })
    }
    // 复制请求返回的口令至剪切板
    const copyClipboard = (record) => {
        getSharVirtualProductPass({
            skuId: record.skuId,
            number: 1
        }).then(res=>{
            if (res.code === 0 ){
                message.success('复制成功')
                copy(res.data.url, {
                    format: 'text/plain',
                });
            }
        })

    }
    return (
        <div className='wrap-box wrap-box-content'>
            <TheQueryForm ref={SearchFormRef} option={searchOption} show onGetValues={(values) => onFormSearch(values)}
                          onReset={(values) => onReset(values)}>
            </TheQueryForm>
            <Space style={{marginBottom: 15}}>
                <TheButton haspermi={['goodsManagement:goodsList:add']} onClick={() => {
                    navigate('/goodsList/addGoods', {state: {mode: 'add'}})
                }}>新建</TheButton>
            </Space>
            <Table
                rowKey={(record) => record.goodsId}
                columns={columns}
                dataSource={dataSource}
                bordered
                pagination={{
                    onChange: pageChange,
                    position: ['bottomCenter'],
                    current: pageData.pageNo,
                    pageSize: pageData.pageSize,
                    total: pageData.total,
                    showSizeChanger: false
                }}/>
            <Modal title='申请上架' open={applyPutAwayModal} onOk={saveApplyPutAway} onCancel={cancelApplyPutAway}
                   okText='申请上架' width={'25%'} confirmLoading={applyPutAwayLoading}>
                <Form layout="vertical" ref={FormRef}>
                    <Form.Item
                        label="申请说明"
                        name="explain"
                        rules={[{required: true},]}
                    >
                        <TextArea style={{height: 100}} showCount maxLength={500} maxlength={500}
                                  placeholder="请输入申请上架的说明"/>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                open={applyRecordModal}
                title=" 申请记录"
                closable={false}
                footer={[<Button key={'index'} onClick={() => {
                    setApplyRecordModal(false)
                }}>我知道了</Button>]}
                destroyOnClose>
                <ApplyRecord storeGoodsId={storeGoodsId}></ApplyRecord>
            </Modal>
            <Modal
                open={copySkuModal}
                onCancel={()=>setCopySkuModal(false)}
                title="复制"
                footer={false}
                destroyOnClose
                width={"70%"}
            >
                <br/>
                <Table dataSource={copyDataSource} columns={copyColumns} bordered rowKey={(r) => r.id} pagination={false} />
            </Modal>
        </div>
    )
}
